define(function () {
	var ec = require('echarts');
	require('echarts/chart/line');
	require('echarts/chart/bar');
	var util = require('dashboard/js/util');
	var zrnumber = require('echarts/util/number');

   	function dealYesterday(data) {
		return $.map(data, function(value){ 
			return value.value;
		});
    }

function UVMinuteChart(id, platform){
	this.id = id;
	this.platform=platform;
	this.initDataChart = {
		time : [],
		pdata : [],
		ndata : []
	}
	this.nowTime = 0;
	this.chart = ec.init(document.getElementById(id));
}
  

	 UVMinuteChart.prototype.init = function () {
        var self = this;
        var initDataChart=self.initDataChart;	

		/* content - chart */
		$.ajax({
			type: 'post',
			url: '/dashboard/realtime/netflow/getUVByMinYestoday',
            jsonp: "callback",
            jsonpCallback: "jsonpCallback",
            dataType: "json",
            data: {platform:self.platform},
            async: false,
			success: function(json){
               	// json = JSON.parse(json.responseText);
               	initDataChart.pdata = dealYesterday(json.data);
               	$.ajax({
					type: 'post',
					url: '/dashboard/realtime/netflow/getUVByMin',
					jsonp: "callback",
					jsonpCallback:"jsonpCallback",
					dataType: "json",
					data:{platform:self.platform},
					async:false,
					success: function(json){ 
						renderEchart(self,json.data,'init');
					}
				})
            } 
		})

	}

    //  渲染echart
   	function renderEchart(chart, rdata, flag) {
        // echart初始化
        var self = chart;
        var curID=self.id;
        var initDataChart=self.initDataChart;
         var myChart =self.chart; 

            var option = {
			    tooltip : {
			        trigger: 'axis',
			    },
			    legend: {
			        data:['今日UV','昨日UV'],
			        x: 'center',
			        y: 'bottom',
			        padding: [0,20,0,0],
			        textStyle: {
			        	color: '#818181'
			        }
			    },
				title: {
					x: 60,
					y: 40,
					textStyle:{

						fontWeight: 'bolder',
						color: '#999999'
					}	
				},
				grid: {
					x: 70,
					y: 80,
					y2: 40,
					x2: 35
				},
			    toolbox: {
			        show : false
			    },
			    color: ['#ea6004','#213f51'],
			    calculable : true,
			    animation: false,
			    xAxis : [
			        {
			            type : 'category',
			            boundaryGap : false,
			            splitLine : {
			            	lineStyle : {
			            		color : '#242424'
			            	}
			            },
			            axisLine : {
			            	lineStyle : {
			            		color : '#424242'
			            	}
			            },
			            axisLabel : {
			            	textStyle : {
			            		color : '#7e7e7e'
			            	},
			            	interval: 59,
			            	formatter: function(value){
			            		return value.substr(0,2);
			            	}
			            },
			            data: function() {
			                var x = [];
			                for (var i = 0; i < 24; i++) {
			                	for (var j =0; j < 60; j++){
			                		var hour = i < 10 ? '0'+i.toString() : i.toString();
			                		var min = j <10 ? '0'+j.toString() : j.toString();
			                		x.push(hour+':'+min);
			                	}
			                }
			                return x;
			            }()
			        }
			    ],
			    yAxis : [
			        {
			            type : 'value',
			            axisLine : {
			            	lineStyle : {
			            		color : '#424242'
			            	}
			            },
			            axisLabel : {
			            	textStyle : {
			            		color : '#7e7e7e'
			            	}
			            },
			            splitLine : {
			            	lineStyle : {
			            		color : '#242424'
			            	}
			            },
			        }
			    ],
			    series : [
			        {
			            name:'今日UV',
			            type:'line',
			            smooth:true,
            			symbol:'none',
			            itemStyle: {
			            	normal: {
			            		areaStyle: {type:'default'}
			            	}
			            },
			            data:[],
			            markPoint: {
			            	data: [
			            	{
			                    name: '截止当前',
			                    clickable: false,
			                    symbol:'pin',
			                    symbolSize:30,
		                    	xAxis : '',
		                    	yAxis : '',
			                    itemStyle:{
			                    	normal:{
			                        	color: '#0c0c0c',
			                    		borderColor: '#757575',
			                    		borderWidth: '1',
										label: {
			                    			textStyle: {fontSize:13,color:'#999999'},
			                    			formatter: function(mdata){
			                    				return ' ' + zrnumber.addCommas(mdata.value) + ' ';
			                    			}
			                    		}
			                        },
			                        emphasis:{
			                        	borderWidth: '1',
			                        	label: { textStyle: {fontSize:13}}
			                        }
			                    }
			                },
			                {
			                	name: '当前点',
			                	symbol: 'circle', 
			                	symbolSize: 8,
                     			effect:{show:true,type:'bounce'},
                     			itemStyle:{normal:{color:'#e26d1e',borderColor:'#848484',borderWidth:4}}
			                }]
			            },
			        },
			        {
			            name:'昨日UV',
			            type:'line',
			            smooth:true,
            			symbol:'none',
			            itemStyle: {
			            	normal: {
			            		lineStyle:{
			                        width:1
			                    },
			            		areaStyle: {type:'default'}
			            	}
			            },
			            data:[]
			        }
			    ]
            };
    		
    		if (flag == 'init') {
    			var initNdata = [], initTime = [];
    			$.each(rdata, function(key, value){  
    				initNdata.push(value.value);
    				initTime.push(value.time);
    			});
    			initDataChart.ndata = initNdata;
    			initDataChart.time = initTime;
    			option.series[1].data = initDataChart.pdata;
				option.series[0].data = initNdata;
				option.title.text = title[self.platform];
				var curVal = option.series[0].data[option.series[0].data.length-1];
				option.series[0].markPoint.data[0].xAxis = util.timeToHour(initDataChart.time[initDataChart.time.length-1]);
				option.series[0].markPoint.data[0].yAxis = curVal * 1.01;
				option.series[0].markPoint.data[0].value = option.series[0].data[option.series[0].data.length-1];
				option.series[0].markPoint.data[1].xAxis = util.timeToHour(initDataChart.time[initDataChart.time.length-1]);
				option.series[0].markPoint.data[1].yAxis = option.series[0].data[option.series[0].data.length-1];
    			// option.series[0].markPoint.data[1].value = option.series[0].data[option.series[0].data.length-1];
    			self.nowTime = initDataChart.time[initDataChart.time.length-1];
				// var now = new Date();
				// now.setTime(nowTime);
				// $('#dataRealtime').html(now.toLocaleDateString().replace(/\//g,'-') + ' ' + now.toTimeString().substr(0,8));
    		} else {
    			option.series[1].data = initDataChart.pdata;
				option.series[0].data = initDataChart.ndata;
				option.title.text = title[self.platform];
				var curVal = option.series[0].data[option.series[0].data.length-1];
    			option.series[0].markPoint.data[0].xAxis = util.timeToHour(initDataChart.time[initDataChart.time.length-1]);
				option.series[0].markPoint.data[0].yAxis = curVal * 1.01;
    			option.series[0].markPoint.data[1].xAxis = util.timeToHour(initDataChart.time[initDataChart.time.length-1]);
				option.series[0].markPoint.data[1].yAxis = option.series[0].data[option.series[0].data.length-1];
    			// option.series[0].markPoint.data[1].value = option.series[0].data[option.series[0].data.length-1];
    			if (flag == 'addpin') {
    				var sum = rdata[rdata.length-1].value;
    				option.series[0].markPoint.data[0].value = sum;
    			} else {
    				option.series[0].markPoint.data[0].value = option.series[0].data[option.series[0].data.length-1];
    			}
    		}
            // 为echarts对象加载数据 
            myChart.setOption(option); 
    }
	 
	 function refreshBy2(chart) {
        var self = chart;
        var initDataChart=self.initDataChart;	 	
		/* content - chart */
		var theDate = new Date();
		theDate.setTime(self.nowTime);
		if ( theDate.getHours() == 0 && theDate.getMinutes() == 0 && (theDate.getSeconds() == 0 || theDate.getSeconds() == 1) ) {
			initDataChart.time = [];
			initDataChart.pdata = [];
			initDataChart.ndata = [];
			$.ajax({
				type: 'post',
				url: '/dashboard/realtime/netflow/getUVByMinYestoday',
	            jsonp: "callback",
	            jsonpCallback: "jsonpCallback",
	            dataType: "json",
	            data: {platform:self.platform},
	            async: false,
				success: function(json){
	               	// json = JSON.parse(json.responseText);
	               	initDataChart.pdata = dealYesterday(json.data);
	               	$.ajax({
						type: 'post',
						url: '/dashboard/realtime/netflow/getUVByMin',
						jsonp: "callback",
						jsonpCallback:"jsonpCallback",
						dataType: "json",
						data:{platform:self.platform},
						async:false,
						success: function(json){ 
							renderEchart(self,json.data,'init');
						}
					})
	            } 
			})
		} else {
			$.ajax({
				type: 'post',
				url: '/dashboard/realtime/netflow/getUVHourData',
	            jsonp: "callback",
	            jsonpCallback: "jsonpCallback",
	            dataType: "json",
	            data: {platform:self.platform, time: theDate.getTime()},
	            async: false,
				success: function(json){ 
					var differ = (json.data[json.data.length-1].time - theDate.getTime())/1000;
					if (differ > 60) {
						$.ajax({
							type: 'post',
							url: '/dashboard/realtime/netflow/getUVByMin',
				            jsonp: "callback",
				            jsonpCallback:"jsonpCallback",
				            dataType: "json",
				            data:{platform:self.platform, time:self.nowTime},
				            async:false,
							success: function(data){ 
								// console.log("data time "+ data.data[data.data.length-1].time);
								// console.log("initDataChart time " + initDataChart);
								var length = initDataChart.time.length
								if(length > 0 && initDataChart.time[length-1] < data.data[0].time){
									initDataChart.time.push(data.data[0].time);
									initDataChart.ndata.push(data.data[0].value);
									renderEchart(self,initDataChart,'refresh');
								}
							}
						});
						self.nowTime += 60000;
					} else {
						renderEchart(self,json.data,'addpin');
					}
				},
	            error: function(json){ }
	        })
	    }
	}


// 对Date的扩展，将 Date 转化为指定格式的String 
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.format= function(fmt) 
{ //author: meizz 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); 
  return fmt; 
}


	function flushTotal() {
		$.ajax({
			url: '/dashboard/realtime/netflow/getUV',
			type: 'POST',
			async: true,
			dataType: 'json',
			success: function(data) {
				$('#uv_all').html(zrnumber.addCommas(data.data[0].value));
				var now = new Date();
				now.setTime(data.time);
				$('#dataRealtime').html(now.format("yyyy-MM-dd hh:mm:ss"));
			},
			timeout: 10000
		});
	}

	var title = {
		"": '总体',
		"PC": 'PC',
		"M": 'M',
		"APP": 'APP'
	}


	var chart_all=new UVMinuteChart("all","");	
	var chart_pc=new UVMinuteChart("pc","PC");
	var chart_m=new UVMinuteChart("m","M");	
	var chart_app=new UVMinuteChart("app","APP");
	var charts=[chart_all, chart_pc, chart_m, chart_app];
	// var charts=[chart_pc, chart_m];

	function render() {
		
		for(var i=0; i<charts.length; i++){		
			charts[i].init();
		}
		refreshTotalUV();
		refreshChart();
	}

	function refreshTotalUV(){
			flushTotal();
			var timeTicket = setInterval(function() {
				flushTotal()
			}, 11 * 1000);

	}

	function refreshChart() {
		clearInterval(timeTicket2);
		var timeTicket2 = setInterval(function(){refreshBy2(charts[0])}, 10000);
		timeTicket2 = setInterval(function(){refreshBy2(charts[1])}, 10000);
		timeTicket2 = setInterval(function(){refreshBy2(charts[2])}, 10000);
		timeTicket2 = setInterval(function(){refreshBy2(charts[3])}, 10000);
	}
    $(window).resize(function(){
        $.each(charts,function(i,n){
            n.chart.resize();
        });
    });
	return {
		render: render
	};
})